package com.example.shutdown_v1.controller;

import com.example.shutdown_v1.constants.PowerDeviceConstants;
import com.example.shutdown_v1.service.PowerDeviceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 电力设备控制器
 * 提供电力查询和状态管理API
 */
@RestController
@RequestMapping("/api/power-device")
@Slf4j
@RequiredArgsConstructor
@CrossOrigin(originPatterns = "*")
public class PowerDeviceController {
    
    private final PowerDeviceService powerDeviceService;
    
    /**
     * 获取电力设备列表
     * @return 电力设备列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getPowerDeviceList() {
        try {
            log.debug("[API] 获取电力设备列表");
            
            // 这里可以从数据库或配置中获取商家列表
            // 暂时返回模拟数据，实际应该从数据库查询
            java.util.List<Map<String, Object>> devices = new java.util.ArrayList<>();
            
            // 示例：添加一个商家的电力设备
            devices.add(Map.of(
                "merchantId", "merchant_001",
                "merchantName", "星巴克咖啡(一楼店)",
                "allPowerOff", false,
                "hasData", true,
                "updateTime", java.time.LocalDateTime.now().toString()
            ));
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", devices,
                "message", "获取设备列表成功"
            ));
            
        } catch (Exception e) {
            log.error("[API] 获取设备列表失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取设备列表失败: " + e.getMessage(),
                "data", java.util.Collections.emptyList()
            ));
        }
    }
    
    /**
     * 查询单路电力状态（同步等待响应）
     * @param merchantId 商家ID
     * @param channel 路数 (1-6)
     * @return 实际电路状态
     */
    @PostMapping("/{merchantId}/query/{channel}/sync")
    public ResponseEntity<Map<String, Object>> querySingleChannelSync(
            @PathVariable String merchantId, 
            @PathVariable Integer channel) {
        try {
            log.info("[API同步] 查询单路电力并等待响应 - 商家:{}, 路数:{}", merchantId, channel);
            
            // 验证路数范围
            if (channel < 1 || channel > PowerDeviceConstants.MAX_CHANNELS) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false, 
                    "message", "路数必须在1-" + PowerDeviceConstants.MAX_CHANNELS + "之间"
                ));
            }
            
            // 发送查询指令
            powerDeviceService.querySingleChannel(merchantId, channel);
            
            // 等待响应（最多10秒）
            Boolean result = powerDeviceService.waitForChannelResponse(merchantId, channel, 10000);
            
            if (result == null) {
                return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "设备未响应：超时或设备未接入",
                    "merchantId", merchantId,
                    "channel", channel,
                    "deviceStatus", "设备未接入或响应超时"
                ));
            }
            
            // 查询成功后，直接返回完整的商家状态信息
            Map<String, Object> fullStatus = powerDeviceService.getMerchantPowerStatus(merchantId);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "查询成功",
                "queryChannel", channel,
                "channelResult", Map.of(
                    "powerOn", result,
                    "powerStatus", result ? "有电" : "断电",
                    "triggerStatus", result ? "触发" : "非触发"
                ),
                "merchantStatus", fullStatus  // 包含完整的商家状态
            ));
            
        } catch (Exception e) {
            log.error("[API同步] 单路查询失败 - 商家:{}, 路数:{}", merchantId, channel, e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false, 
                "message", "查询失败: " + e.getMessage(),
                "merchantId", merchantId,
                "channel", channel
            ));
        }
    }
    
    /**
     * 查询所有路电力状态（同步执行）
     * @param merchantId 商家ID
     * @return 完整查询结果
     */
    @PostMapping("/{merchantId}/query/all/sync")
    public ResponseEntity<Map<String, Object>> queryAllChannelsSync(@PathVariable String merchantId) {
        try {
            log.info("[API同步] 查询全路电力并等待响应 - 商家:{}", merchantId);
            
            // 同步执行全路查询
            CompletableFuture<Map<Integer, Boolean>> future = powerDeviceService.queryAllChannels(merchantId);
            Map<Integer, Boolean> results = future.get(); // 等待完成
            
            // 查询完成后，直接返回完整的商家状态信息
            Map<String, Object> fullStatus = powerDeviceService.getMerchantPowerStatus(merchantId);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "全路查询完成",
                "merchantId", merchantId,
                "queryResults", results,
                "merchantStatus", fullStatus  // 包含完整的商家状态
            ));
            
        } catch (Exception e) {
            log.error("[API同步] 全路查询失败 - 商家:{}", merchantId, e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false, 
                "message", "查询失败: " + e.getMessage(),
                "merchantId", merchantId
            ));
        }
    }
    
    /**
     * 获取商家当前电力状态
     * @param merchantId 商家ID
     * @return 电力状态信息
     */
    @GetMapping("/{merchantId}/status")
    public ResponseEntity<Map<String, Object>> getPowerStatus(@PathVariable String merchantId) {
        try {
            log.debug("[API] 获取电力状态 - 商家:{}", merchantId);
            
            Map<String, Object> status = powerDeviceService.getMerchantPowerStatus(merchantId);
            
            return ResponseEntity.ok(Map.of(
                "success", true, 
                "data", status,
                "message", "状态获取成功"
            ));
            
        } catch (Exception e) {
            log.error("[API] 获取状态失败 - 商家:{}", merchantId, e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false, 
                "message", "获取状态失败: " + e.getMessage(),
                "merchantId", merchantId
            ));
        }
    }
    
    /**
     * 获取支持的路数配置信息
     * @return 配置信息
     */
    @GetMapping("/config")
    public ResponseEntity<Map<String, Object>> getConfig() {
        return ResponseEntity.ok(Map.of(
            "success", true,
            "data", Map.of(
                "maxChannels", PowerDeviceConstants.MAX_CHANNELS,
                "supportedChannels", PowerDeviceConstants.QUERY_COMMANDS.keySet(),
                "queryTimeout", PowerDeviceConstants.QUERY_TIMEOUT_MS + "ms",
                "commandInterval", PowerDeviceConstants.COMMAND_INTERVAL_MS + "ms",
                "currentTopics", Map.of(
                    "command", PowerDeviceConstants.Topics.CURRENT_COMMAND_TOPIC,
                    "response", PowerDeviceConstants.Topics.CURRENT_RESPONSE_TOPIC
                )
                // 将来版本的主题配置 (暂时注释)
                /*
                "futureTopics", Map.of(
                    "commandFormat", PowerDeviceConstants.Topics.FUTURE_COMMAND_TOPIC_FORMAT,
                    "responsePattern", PowerDeviceConstants.Topics.FUTURE_RESPONSE_TOPIC_PATTERN
                )
                */
            )
        ));
    }
}
